<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useWatermarkStore } from '../../store/useWatermarkStore'
import { ProcessStatus } from '../../types'
import { formatFileSize } from '../../utils'

const store = useWatermarkStore()
const uploadRef = ref<HTMLInputElement | null>(null)

// 最大文件大小 (50MB)
const MAX_FILE_SIZE = 50 * 1024 * 1024

// 触发文件选择
const handleClick = () => {
  uploadRef.value?.click()
}

// 文件选择处理
const handleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (!input.files || input.files.length === 0) return
  
  const file = input.files[0]
  
  // 检查文件大小
  if (file.size > MAX_FILE_SIZE) {
    ElMessage.error(`文件过大，请选择小于 ${formatFileSize(MAX_FILE_SIZE)} 的文件`)
    return
  }
  
  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  const isVideo = file.type.startsWith('video/')
  
  if (!isImage && !isVideo) {
    ElMessage.error('只支持图片和视频文件')
    return
  }
  
  // 添加到store
  store.addFile({
    name: file.name,
    size: file.size,
    type: file.type,
    status: ProcessStatus.IDLE,
    url: URL.createObjectURL(file)
  })
  
  // 重置input，允许重复选择相同文件
  if (uploadRef.value) {
    uploadRef.value.value = ''
  }
}
</script>

<template>
  <div class="file-uploader">
    <input
      ref="uploadRef"
      type="file"
      accept="image/*,video/*"
      class="hidden"
      @change="handleFileChange"
    />
    <div
      class="upload-area"
      @click="handleClick"
      @dragover.prevent
      @drop.prevent="(e) => e.dataTransfer?.files.length && handleFileChange({ target: { files: e.dataTransfer.files } } as any)"
    >
      <el-icon class="upload-icon"><upload-filled /></el-icon>
      <p class="upload-text">点击或拖拽文件到此处上传</p>
      <p class="upload-hint">支持图片和视频文件，最大 {{ formatFileSize(MAX_FILE_SIZE) }}</p>
    </div>
  </div>
</template>

<style scoped>
.file-uploader {
  width: 100%;
  margin-bottom: 1rem;
}

.hidden {
  display: none;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 2rem;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  background-color: #f5f7fa;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-icon {
  font-size: 3rem;
  color: #909399;
  margin-bottom: 1rem;
}

.upload-text {
  font-size: 1rem;
  margin-bottom: 0.5rem;
  color: #303133;
}

.upload-hint {
  font-size: 0.875rem;
  color: #909399;
}
</style> 